package me.macd.util.dbutil;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import javax.sql.DataSource;
import java.io.Closeable;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @author macd
 * @version 1.0 [2019-06-10 22:45]
 **/
public class DB implements Closeable {
    //private DataSource dataSource;
    private Connection connection;

    public DB(DataSource dataSource) throws SQLException {
        //this.dataSource = dataSource;
        this.connection = dataSource.getConnection();
    }

    public DB(Connection connection) {
        this.connection = connection;
    }

    public void close() throws IOException {
        try {
            DbUtils.close(connection);
        } catch (SQLException ex) {
            throw new IOException("close connection error", ex);
        }
    }

    public int update(String sql, Object... args) throws SQLException {
        QueryRunner run = new QueryRunner();
        return run.update(connection, sql, args);
    }

    public <T> T queryForObject(String sql, Class<T> clazz, Object... args) throws SQLException {
        QueryRunner run = new QueryRunner();
        return run.query(connection, sql, new BeanHandler<>(clazz), args);
    }

    public <T> List<T> queryForList(String sql, Class<T> clazz, Object... args) throws SQLException {
        QueryRunner run = new QueryRunner();
        return run.query(connection, sql, new BeanListHandler<>(clazz), args);
    }

    public void execute(String sql) throws SQLException {
        QueryRunner run = new QueryRunner();
        run.execute(connection, sql);
    }
}
